package com.vtron.web.api.filter;

import com.alibaba.fastjson.JSON;
import com.vtron.core.HttpCode;
import com.vtron.core.HttpResult;
import com.vtron.web.api.service.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * 网络接口鉴权过滤器
 * @date : 2022/4/15 16:48
 * @author: 忻龙彪
 */
@WebFilter(urlPatterns = {"/api/v1/*"})
public class TokenApiFilter implements Filter{

    @Autowired(required = false)
    private ITokenService tokenService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String token = httpServletRequest.getHeader("Authorization");
        HttpCode result = tokenService.check(token);
        if (result.equals(HttpCode.SUCCESS)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            httpServletResponse.setHeader("content-type", "application/json;charset=utf-8");
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,WithCredentials,Authorization");
            PrintWriter out = httpServletResponse.getWriter();
            out.println(JSON.toJSONString(new HttpResult(result,result.getDesc())));
        }
    }

}
